import 'dart:io';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:device_info/device_info.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:extended_image/extended_image.dart';
import 'package:fehviewer/const/const.dart';
import 'package:fehviewer/const/storages.dart';
import 'package:fehviewer/models/index.dart';
import 'package:fehviewer/models/profile.dart';
import 'package:fehviewer/network/gallery_request.dart';
import 'package:fehviewer/store/floor/database.dart';
import 'package:fehviewer/store/get_store.dart';
import 'package:fehviewer/store/hive/hive.dart';
import 'package:fehviewer/utils/http_override.dart';
import 'package:fehviewer/utils/logger.dart';
import 'package:fehviewer/utils/storage.dart';
import 'package:fehviewer/utils/utility.dart';
import 'package:fehviewer/utils/vibrate.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_statusbar_manager/flutter_statusbar_manager.dart';
import 'package:get/get.dart';
import 'package:local_auth/local_auth.dart';
import 'package:logger/logger.dart';
import 'package:package_info/package_info.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';

const int kProxyPort = 4041;

final FirebaseAnalytics analytics = FirebaseAnalytics();
FirebaseFirestore firestore = FirebaseFirestore.instance;
final LocalAuthentication localAuth = LocalAuthentication();
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
// final LanguageIdentifier identifier = LanguageIdentifier();
// final LanguageIdentifier identifier =
//     FirebaseLanguage.instance.languageIdentifier();

final HiveHelper hiveHelper = HiveHelper();

final Global global = Global();

// 全局配置
// ignore: avoid_classes_with_only_static_members
class Global {
  // 是否第一次打开
  static bool isFirstOpen = false;
  static bool inDebugMode = false;
  static bool isFirstReOpenEhSetting = true;

  // static Profile profile = kDefProfile.copyWith(
  //     ehConfig: kDefEhConfig.copyWith(safeMode: Platform.isIOS));
  static Profile profile = kDefProfile.copyWith(ehConfig: kDefEhConfig);

  static List<GalleryCache> galleryCaches = <GalleryCache>[];

  static late CookieManager cookieManager;

  static late PersistCookieJar cookieJar;

  // static HttpProxy httpProxy = HttpProxy('localhost', '$kProxyPort');
  static DFHttpOverrides dfHttpOverrides = DFHttpOverrides();

  static String appSupportPath = '';
  static String appDocPath = '';
  static String tempPath = '';
  static late String extStorePath;
  static String dbPath = '';

  static late PackageInfo packageInfo;

  static bool isDBinappSupportPath = false;

  static bool canCheckBiometrics = false;

  User get user => profile.user;
  set user(User val) => profile = profile.copyWith(user: val);

  static Future<EhDatabase> getDatabase() async {
    return await $FloorEhDatabase
        .databaseBuilder(Global.dbPath)
        .addMigrations(ehMigrations)
        .build();
  }

  // init
  static Future<void> init() async {
    // 判断是否debug模式
    inDebugMode = EHUtils().isInDebugMode;

    await FlutterDownloader.initialize(debug: Global.inDebugMode);

    canCheckBiometrics = await localAuth.canCheckBiometrics;

    //statusBar设置为透明，去除半透明遮罩
    SystemChrome.setSystemUIOverlayStyle(
        const SystemUiOverlayStyle(statusBarColor: Colors.transparent));
    // await FlutterStatusbarManager.setTranslucent(false);
    // await FlutterStatusbarManager.setColor(Colors.green);
    // await FlutterStatusbarManager.setNavigationBarColor(Colors.green);

    appSupportPath = (await getApplicationSupportDirectory()).path;
    appDocPath = (await getApplicationDocumentsDirectory()).path;
    tempPath = (await getTemporaryDirectory()).path;
    extStorePath = !Platform.isIOS
        ? (await getExternalStorageDirectory())?.path ?? ''
        : '';

    packageInfo = await PackageInfo.fromPlatform();

    initLogger();
    if (!inDebugMode) {
      Logger.level = Level.info;
      initLogger();
    }

    // 代理初始化
    // if (Platform.isIOS || Platform.isAndroid) {
    //   await CustomHttpsProxy.instance.init();
    // }

    logger.i('doc $appDocPath \napps $appSupportPath \ntemp $tempPath');

    dbPath = path.join(Global.appSupportPath, EHConst.DB_NAME);

    // SP初始化
    await StorageUtil.init();

    await GStore.init();

    await HiveHelper.init();

    await vibrateUtil.init();

    _profileInit();

    cookieManager = CookieManager(await Api.cookieJar);
    cookieJar = await Api.cookieJar;

    // 读取设备第一次打开
    isFirstOpen = !StorageUtil().getBool(STORAGE_DEVICE_ALREADY_OPEN_KEY);
    if (isFirstOpen) {
      creatDirs();
      StorageUtil().setBool(STORAGE_DEVICE_ALREADY_OPEN_KEY, true);
    }

    isDBinappSupportPath = StorageUtil().getBool(IS_DB_IN_SUPPORT_DIR);

    // 数据更新
    // await dataUpdate();

    _initImageHttpClient();
  }

  static void creatDirs() {
    final Directory downloadDir = Directory(path.join(appDocPath, 'Download'));
    downloadDir.create();
  }

  /// profile初始化
  static Future<void> _profileInit() async {
    await _checkReset();

    _initProfile();

    // if ((profile.dnsConfig.enableCustomHosts ?? false) ||
    //     (profile.dnsConfig.enableDoH ?? false)) {
    //   logger.v('${profile.dnsConfig.enableCustomHosts}');
    //   HttpOverrides.global = httpProxy;
    // }

    if (profile.dnsConfig.enableDomainFronting ?? false) {
      logger.d('enableDomainFronting');
      HttpOverrides.global = dfHttpOverrides;
    }
  }

  static void _initProfile() {
    final GStore gStore = Get.find<GStore>();
    profile = gStore.profile;
  }

  // 持久化Profile信息
  static Future<void>? saveProfile() {
    // logger.d(profile.toJson());
    final GStore gStore = Get.find<GStore>();
    gStore.profile = profile;
  }

  static Future<void> _checkReset() async {
    final String cleanVer = StorageUtil().getString(CLEAN_VER) ?? '0';

    if (double.parse(cleanVer) < EHConst.cleanDataVer) {
      logger.d('clean');
      profile = kDefProfile;
      saveProfile();
      StorageUtil().setString(CLEAN_VER, '${EHConst.cleanDataVer}');
    }
  }

  static void _initImageHttpClient() {
    final HttpClient eClient =
        ExtendedNetworkImageProvider.httpClient as HttpClient;
    eClient.badCertificateCallback =
        (X509Certificate cert, String host, int port) {
      return true;
    };
  }
}
